//
//  GWAlbumCoversView.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/5.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

protocol GWAlbumCoversViewDelegate {
  func gwAlbumCoversView(_ view: GWAlbumCoversView, selectedWithAlbumIdentifier: Int)
}

class GWAlbumCoversView: UIView {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var stackView: UIStackView!
  @IBOutlet private weak var stackViewLeadingConstraint: NSLayoutConstraint!
  @IBOutlet private weak var stackViewTrailingConstraint: NSLayoutConstraint!
  
  
  // MARK: - Private vars
  
  
  
  // MARK: - Private methods
  
  
  
  // MARK: - Public vars
  
  var delegate: GWAlbumCoversViewDelegate?
  
  // MARK: - Lifecycle
  
  
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  func prepare(albums: [Album]) {
    subviews.forEach {
      if type(of: $0) == GWAlbumCoverItem.self {
        $0.removeFromSuperview()
      }
    }
    for (index, album) in albums.enumerated() {
      if index < 3 {
        let item: GWAlbumCoverItem = .fromNib()
        item.delegate = self
        item.prepare(album: album)
        stackView.addArrangedSubview(item)
        let witdh = (UIScreen.main.bounds.width - 16 * 2) * 0.9 / 3
        item.snp.makeConstraints { maker in
          maker.width.equalTo(witdh)
        }
        let padding = (UIScreen.main.bounds.width - 16 * 2) * 0.1 / 4
        stackViewLeadingConstraint.constant = padding
        stackViewTrailingConstraint.constant = padding
      } else {
        break
      }
    }
  }
}

extension GWAlbumCoversView {
  static var defaultHeight: CGFloat = (UIScreen.main.bounds.width - 16 * 2) * 0.9 / 3 + 40
}

// MARK: - GWAlbumCoversViewDelegate

extension GWAlbumCoversView: GWAlbumCoverItemDelegate {
  func gwAlbumCoverItem(_ item: GWAlbumCoverItem, tappedWithAlbumIdentifier: Int) {
    delegate?.gwAlbumCoversView(self, selectedWithAlbumIdentifier: tappedWithAlbumIdentifier)
  }
}
